<template>
  <div class="article-list-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>健康文章管理</span>
          <el-button type="primary" @click="showAddArticleDialog">新增文章</el-button>
        </div>
      </template>
      
      <!-- 搜索和筛选 -->
      <div class="search-filter">
        <el-input v-model="searchQuery" placeholder="搜索文章标题" prefix-icon="Search" style="width: 300px; margin-right: 15px;"></el-input>
        <el-select v-model="selectedCategory" placeholder="选择文章分类" style="width: 200px; margin-right: 15px;">
          <el-option label="全部" value=""></el-option>
          <el-option label="运动健康" value="exercise"></el-option>
          <el-option label="鼻炎护理" value="rhinitis"></el-option>
          <el-option label="饮食健康" value="diet"></el-option>
          <el-option label="生活习惯" value="lifestyle"></el-option>
        </el-select>
        <el-button type="primary" @click="handleSearch">搜索</el-button>
        <el-button @click="resetSearch">重置</el-button>
      </div>
      
      <!-- 文章表格 -->
      <el-table :data="articlesData" style="width: 100%">
        <el-table-column prop="id" label="文章ID" width="80"></el-table-column>
        <el-table-column prop="title" label="文章标题" min-width="200">
          <template #default="scope">
            <div class="title-preview" :title="scope.row.title">
              {{ scope.row.title }}
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="category" label="文章分类" width="120">
          <template #default="scope">
            <el-tag :type="getCategoryType(scope.row.category)">
              {{ getCategoryName(scope.row.category) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="author" label="作者" width="120"></el-table-column>
        <el-table-column prop="readCount" label="阅读量" width="100"></el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.status === 'published' ? 'success' : 'warning'">
              {{ scope.row.status === 'published' ? '已发布' : '草稿' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createdAt" label="创建时间" width="180"></el-table-column>
        <el-table-column label="操作" width="150">
          <template #default="scope">
            <el-button type="primary" size="small" @click="showEditArticleDialog(scope.row)">编辑</el-button>
            <el-button :type="scope.row.status === 'published' ? 'warning' : 'success'" size="small" @click="handleToggleStatus(scope.row)">
              {{ scope.row.status === 'published' ? '下架' : '发布' }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        ></el-pagination>
      </div>
    </el-card>
    
    <!-- 新增/编辑文章对话框 -->
    <el-dialog v-model="articleDialogVisible" :title="dialogTitle" width="800px">
      <el-form :model="articleForm" :rules="articleRules" ref="articleFormRef" label-width="120px">
        <el-form-item label="文章标题" prop="title">
          <el-input v-model="articleForm.title" placeholder="请输入文章标题"></el-input>
        </el-form-item>
        <el-form-item label="文章分类" prop="category">
          <el-select v-model="articleForm.category" placeholder="请选择文章分类">
            <el-option label="运动健康" value="exercise"></el-option>
            <el-option label="鼻炎护理" value="rhinitis"></el-option>
            <el-option label="饮食健康" value="diet"></el-option>
            <el-option label="生活习惯" value="lifestyle"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="作者" prop="author">
          <el-input v-model="articleForm.author" placeholder="请输入作者名称"></el-input>
        </el-form-item>
        <el-form-item label="文章摘要" prop="summary">
          <el-input v-model="articleForm.summary" type="textarea" :rows="3" placeholder="请输入文章摘要"></el-input>
        </el-form-item>
        <el-form-item label="文章内容" prop="content">
          <el-input v-model="articleForm.content" type="textarea" :rows="10" placeholder="请输入文章内容"></el-input>
        </el-form-item>
        <el-form-item label="状态">
          <el-switch v-model="articleForm.status" active-value="published" inactive-value="draft"></el-switch>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="articleDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSaveArticle">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed } from 'vue'
import { ElMessage } from 'element-plus'
import axios from 'axios'

// 搜索和筛选条件
const searchQuery = ref('')
const selectedCategory = ref('')

// 表格数据
const articlesData = ref([])
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(20)

// 对话框状态
const articleDialogVisible = ref(false)
const editingArticleId = ref(null)
const articleFormRef = ref()

// 文章表单
const articleForm = reactive({
  title: '',
  category: '',
  author: '',
  summary: '',
  content: '',
  status: 'draft'
})

// 表单验证规则
const articleRules = {
  title: [
    { required: true, message: '请输入文章标题', trigger: 'blur' },
    { min: 5, max: 200, message: '文章标题长度在 5 到 200 个字符', trigger: 'blur' }
  ],
  category: [
    { required: true, message: '请选择文章分类', trigger: 'change' }
  ],
  author: [
    { required: true, message: '请输入作者名称', trigger: 'blur' }
  ],
  summary: [
    { required: true, message: '请输入文章摘要', trigger: 'blur' },
    { min: 10, max: 500, message: '文章摘要长度在 10 到 500 个字符', trigger: 'blur' }
  ],
  content: [
    { required: true, message: '请输入文章内容', trigger: 'blur' },
    { min: 100, message: '文章内容至少 100 个字符', trigger: 'blur' }
  ]
}

// 对话框标题
const dialogTitle = computed(() => {
  return editingArticleId.value ? '编辑文章' : '新增文章'
})

// 获取分类标签类型
const getCategoryType = (category) => {
  const typeMap = {
    'exercise': 'success',
    'rhinitis': 'warning',
    'diet': 'info',
    'lifestyle': 'primary'
  }
  return typeMap[category] || 'primary'
}

// 获取分类名称
const getCategoryName = (category) => {
  const nameMap = {
    'exercise': '运动健康',
    'rhinitis': '鼻炎护理',
    'diet': '饮食健康',
    'lifestyle': '生活习惯'
  }
  return nameMap[category] || category
}

// 获取文章列表
const fetchArticles = () => {
  // 实际项目中应该从后端获取数据
  // 这里使用模拟数据
  const mockData = [
    {
      id: 1,
      title: '提肛运动的正确方法与健康益处',
      category: 'exercise',
      author: '健康专家',
      readCount: 2580,
      status: 'published',
      createdAt: '2023-07-01 10:00:00'
    },
    {
      id: 2,
      title: '季节性鼻炎的预防与护理指南',
      category: 'rhinitis',
      author: '耳鼻喉科医生',
      readCount: 1850,
      status: 'published',
      createdAt: '2023-07-02 11:00:00'
    },
    {
      id: 3,
      title: '健康饮食：远离三高的饮食习惯',
      category: 'diet',
      author: '营养师',
      readCount: 1250,
      status: 'published',
      createdAt: '2023-07-03 12:00:00'
    },
    {
      id: 4,
      title: '良好生活习惯对慢性病预防的重要性',
      category: 'lifestyle',
      author: '健康专家',
      readCount: 980,
      status: 'published',
      createdAt: '2023-07-04 13:00:00'
    }
  ]
  
  // 应用搜索和筛选
  let filteredData = [...mockData]
  if (searchQuery.value) {
    filteredData = filteredData.filter(article => 
      article.title.includes(searchQuery.value)
    )
  }
  if (selectedCategory.value) {
    filteredData = filteredData.filter(article => article.category === selectedCategory.value)
  }
  
  total.value = filteredData.length
  
  // 分页
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  articlesData.value = filteredData.slice(start, end)
}

// 显示新增文章对话框
const showAddArticleDialog = () => {
  editingArticleId.value = null
  // 重置表单
  if (articleFormRef.value) {
    articleFormRef.value.resetFields()
  }
  // 重置表单数据
  articleForm.title = ''
  articleForm.category = ''
  articleForm.author = ''
  articleForm.summary = ''
  articleForm.content = ''
  articleForm.status = 'draft'
  articleDialogVisible.value = true
}

// 显示编辑文章对话框
const showEditArticleDialog = (article) => {
  editingArticleId.value = article.id
  articleForm.id = article.id
  articleForm.title = article.title
  articleForm.category = article.category
  articleForm.author = article.author
  articleForm.summary = article.summary || ''
  articleForm.content = article.content || ''
  articleForm.status = article.status
  articleDialogVisible.value = true
}

// 保存文章
const handleSaveArticle = () => {
  articleFormRef.value.validate((valid) => {
    if (valid) {
      // 实际项目中应该调用API保存数据
      ElMessage.success(editingArticleId.value ? '文章编辑成功' : '文章新增成功')
      articleDialogVisible.value = false
      fetchArticles()
    }
  })
}

// 切换文章状态
const handleToggleStatus = (article) => {
  const newStatus = article.status === 'published' ? 'draft' : 'published'
  // 实际项目中应该调用API更新状态
  ElMessage.success(`文章已${newStatus === 'published' ? '发布' : '下架'}`)
  fetchArticles()
}

// 处理搜索
const handleSearch = () => {
  currentPage.value = 1
  fetchArticles()
}

// 重置搜索
const resetSearch = () => {
  searchQuery.value = ''
  selectedCategory.value = ''
  currentPage.value = 1
  fetchArticles()
}

// 分页处理
const handleSizeChange = (size) => {
  pageSize.value = size
  fetchArticles()
}

const handleCurrentChange = (current) => {
  currentPage.value = current
  fetchArticles()
}

// 初始化数据
fetchArticles()
</script>

<style scoped>
.article-list-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-filter {
  margin-bottom: 20px;
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 10px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.title-preview {
  word-break: break-word;
  color: #303133;
}
</style>